#!/usr/bin/env python 2.7
# -*- coding: utf-8 -*-
# @Time      :2021/6/8
# @Author    :zhangxuchuo
# @Email     :zhangxuchuo@bbdservice.com
# @File      :IC109_Ind6MonsExpLoanAmt
# @Software  :PyCharm


'''eof
name:申请人未来6个月到期贷款金额
code:IC109_Ind6MonsExpLoanAmt
tableName:
columnName:
groups:个人征信模块
dependencies:IC_DSJ_2D
type:常用指标
datasourceType:在线指标
description:
eof'''

import json
import re
import sys
import datetime
import pandas as pd

# reload(sys)
# sys.setdefaultencoding('utf-8')

null_type_list = ['', ' ', None, 'null', 'Null', 'NULL', '/', '-', '--', []]


def getTable(data, tableName, occurTimes, iteratorTimes):
    '''
        获取表信息
        :param data:表上层的字典对象
        :param tableName:表的名字
        :param occurTimes:表出现的次数，如果是0代表此表可以不出现，如果是1代表此表必须出现
        :param iteratorTimes:下级字段出现的次数，如果是0代表下级字段可以不出现，如果是1代表下级字段必须出现
        :return:该表全部数据  返回[{}]为异常缺失，返回0为正常缺失，其他返回正常数组
    '''
    try:
        table = data.get(tableName)
        if occurTimes == 0:
            if table is None or (table == "" and iteratorTimes == 0):
                return 0
            elif isinstance(table, list) is False or len(table) == 0 or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
        if occurTimes == 1:
            if table == "" and iteratorTimes == 0:
                return 0
            if table is None or isinstance(table, list) is False or len(table) == 0 \
                    or (table == "" and iteratorTimes == 1):
                return [{}]
            else:
                return table
    except:
        return [{}]


def isFloat(x):
    '''
    判断x为float类型且大于等于0
    :param x:
    :return:
    '''
    try:
        if isinstance(float(x), float) and float(x) >= 0:
            if str(x) in ['inf', 'infinity', 'INF', 'INFINITY', 'True']:
                return False
            else:
                return True
        else:
            return False
    except:
        return False

def Formate(time):
    import re
    import datetime
    r = re.compile(r'\D+')
    try:
        date = datetime.datetime.strptime(time, '%Y.%m.%d').strftime('%Y%m%d')
    except:
        try:
            date = datetime.datetime.strptime(time, '%Y-%m-%d').strftime('%Y%m%d')
        except:
            try:
                date = datetime.datetime.strptime(time, '%Y/%m/%d').strftime('%Y%m%d')
            except:
                try:
                    tmp = r.sub('', time)
                    date = datetime.datetime.strptime(tmp, '%Y%m%d').strftime('%Y%m%d')
                except:
                    date = None
    return date

# 1.FACTOR = sum(相关还款责任信息段(PD03A)·五级分类(PD03AD05)为“2(关注)”的余额（PD03AJ02）)
# 2.五级分类相关缺失值判断（注：非由于五级分类影响产生的缺失值逻辑根据所有指标通用缺失值逻辑确认）：若策略受五级分类为空影响返回缺失值，则判断业务种类是否为81贷记卡、71准贷记卡、82大额专项分期卡，若是则通过，若不是则仍然判断为缺失值；
# list=[]
# IF 五级分类(PD03AD05) 为空 and 业务种类[PD03AD02] in [71,81,82]
# list.append(0)
# elseif 五级分类(PD03AD05) 为空  and 业务种类[PD03AD02] notin [71,81,82]
# list.append(None)

def IC109_Ind6MonsExpLoanAmt():
    data = IC_DSJ_2D.get('data')
    #PDA 借贷账户信息 [1..1]
    PDA = getTable(data, 'PDA', 1, 0)
    account = []
    if PDA == [{}]:
        return '缺失值'
    elif PDA == 0:
        return 0
    else:
        #PD01 借贷账户信息单元 [0..*]
        PD01 = getTable(PDA[0], 'PD01', 0, 0)
        if PD01 == [{}]:
            return '缺失值'
        elif PD01 == 0:
            return 0
        else:
            for i in PD01:
                #PD01A 基本信息段 [1..1]
                PD01A = getTable(i, 'PD01A', 1, 1)
                #PD01B 最新表现信息段 [1..1]
                PD01B = getTable(i, 'PD01B', 1, 1)
                #PD01C 最近一次月度表现信息段
                PD01C = getTable(i, 'PD01C', 0, 1)
                if PD01A == [{}] or PD01A == 0 or PD01B == [{}] or PD01B == 0 or PD01C == [{}] or PD01C == 0:
                    pass
                else:
                    # PD01AD01 账户类型
                    PD01AD01 = PD01A[0].get('PD01AD01')
                    # PD01BD01 账户状态
                    PD01BD01 = PD01B[0].get('PD01BD01')
                    # PD01AR02 到期日期
                    PD01AR02 = PD01A[0].get('PD01AR02')
                    # PD01CR04 信息报告日期
                    PD01CR04 = PD01C[0].get('PD01CR04')
                    #PD01AJ01 借款金额
                    PD01AJ01 = PD01A[0].get('PD01AJ01')
                    print(PD01AR02, PD01CR04)
                    if PD01AD01 not in null_type_list and PD01BD01 not in null_type_list and PD01CR04 not in null_type_list and PD01AJ01 not in null_type_list:
                        if PD01AD01 in ['D1', 'R1', 'R4']:
                            if (PD01AD01 == 'D1' and PD01BD01 not in ['3', '5']) or (PD01AD01 in ['R1', 'R4'] and PD01BD01 not in ['3']) :
                                if Formate(PD01CR04) <= Formate(PD01AR02) <= (datetime.datetime.strptime(PD01CR04, '%Y-%m-%d') + pd.tseries.offsets.DateOffset(months=6)).strftime("%Y%m"):
                                    account.append(float(PD01AJ01))
                    else:
                        account.append('缺失值')


    if len(list(set(account))) == 1 and list(set(account)) == '缺失值':
        return '缺失值'
    else:
        res = [i for i in account if i != '缺失值']
        return sum(res)

result = IC109_Ind6MonsExpLoanAmt()
# if __name__ == '__main__':
#     with open(r'C:\Users\john\Desktop\samples\IC_DSJ_2D.json',encoding='utf8') as ff:
#         dd = json.loads(ff.read())
#     IC_DSJ_2D = dd['IC_DSJ']
#     result = IC109_Ind6MonsExpLoanAmt()
#     print(result)